package com.hutiao.snowhb.common;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

public class ImageUtil {

	
	public static int[] getWightHeight(String file) throws FileNotFoundException, IOException {
		
		File picture = new File(file);
        BufferedImage sourceImg =ImageIO.read(new FileInputStream(picture)); 
//        System.out.println(String.format("%.1f",picture.length()/1024.0));
//        System.out.println(sourceImg.getWidth());
//        System.out.println(sourceImg.getHeight());
        
        int[] size = new int[2];
        size[0] = sourceImg.getWidth();
        size[1] = sourceImg.getHeight();
        
        return size;
	}
	
	public static String getThumb(String file) throws FileNotFoundException, IOException {
		
		
		
		int i = file.lastIndexOf(".");
		String thumbFile = file.substring(0,i) + "_400.jpg";
		
		int[] size = ImageUtil.getWightHeight(file);
		
		if (size[0] > size[1]) {
			Thumbnails.of(file).sourceRegion(Positions.CENTER, size[1], size[1])
			.size(400, 400).keepAspectRatio(false).outputFormat("jpeg").toFile(thumbFile);
		} else if (size[0] < size[1]) {
			Thumbnails.of(file).sourceRegion(Positions.CENTER, size[0], size[0])
			.size(400, 400).keepAspectRatio(false).outputFormat("jpeg").toFile(thumbFile);
		} else {
			Thumbnails.of(file).size(300, 300).outputFormat("jpeg").toFile(thumbFile);
		}
		
		return thumbFile;
	}
	
	
	public static void main(String[] args) {
		String file = "/Applications/XAMPP/xamppfiles/htdocs/test/huodong/ycVGc7yFg4URYatZsGjhnpdThYHERAO1qlv0yapyUUk.jpg";
		
		try {
			ImageUtil.getThumb(file);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//缩放图片
//		Thumbnails.of(file)   
//        .scale(0.25f)  
//        .toFile(thumbFile);
	}
}
